package com.yx.changdao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.entity.*;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.mapper.CommunityResidentMapper;
import com.yx.changdao.common.utils.ExcelImportExportUtils;
import com.yx.changdao.common.utils.Faster;
import com.yx.changdao.common.utils.IDCheck;
import com.yx.changdao.service.*;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: <br/>
 * 居民信息表
 * <p>
 * <br/>
 * @Auther: flexible
 * @create 2020/04/02 13:47
 */
@Service
public class CommunityResidentServiceImpl extends ServiceImpl<CommunityResidentMapper, CommunityResident> implements CommunityResidentService {

    @Autowired
    private GridInfoService gridInfoService;

    @Autowired
    private CommunityVillageService communityVillageService;
    @Autowired
    private CommunityTownshipService communityTownshipService;
    // 社区建筑物表服务
    @Autowired
    private CommunityBuildService communityBuildService;
    // 户信息表服务
    @Autowired
    private CommunityBuildDetailService communityBuildDetailService;
    /**
     * 居民信息表服务
     */
    @Autowired
    private CommunityResidentService communityResidentService;
    /**
     * 字典表服务
     */
    @Autowired
    private SysDictService sysDictService;

    /**
     * 安置
     *
     * @param
     * @return
     */
    @Override
    public Boolean placement(CommunityResident communityResident, Integer buildDetailId) throws AlertException {
        //查出户
        CommunityBuildDetail buildDetail = communityBuildDetailService.getOne(new QueryWrapper<CommunityBuildDetail>().eq(CommunityResident.ID, buildDetailId));
        if (null == buildDetail) {
            return false;
        }
        //查出楼
        CommunityBuild build = communityBuildService.getOne(new QueryWrapper<CommunityBuild>().eq(CommunityBuild.ID, buildDetail.getBuildId()));
        if (null == build) {
            return false;
        }
        //查出网格
        GridInfo gridInfo = gridInfoService.getOne(new QueryWrapper<GridInfo>().eq(GridInfo.ID, build.getGridId()));
        if (null == gridInfo) {
            return false;
        }
        //查出村/社区
        CommunityVillage communityVillage = communityVillageService.getOne(new QueryWrapper<CommunityVillage>()
                .eq(CommunityVillage.ID, gridInfo.getVillageId()));
        if (null == communityVillage) {
            return false;
        }
        //查出乡镇
        CommunityTownship communityTownship = communityTownshipService.getOne(new QueryWrapper<CommunityTownship>().eq(CommunityTownship.ID, communityVillage.getTownShipId()));
        if (null == communityTownship) {
            return false;
        }
        communityResident.setBuildingInformation(buildDetail.getBuildName() + buildDetail.getUnit() + buildDetail.getDoorPlate());
        communityResident.setBuildDetailId(buildDetailId);
        communityResident.setBuildId(build.getId());
        communityResident.setVillageId(communityVillage.getId());
        communityResident.setTownShipId(communityTownship.getId());
        communityResident.setGridId(gridInfo.getId());
        boolean b = communityResidentService.updateById(communityResident);
        if (!b) {
            throw new AlertException("居民安置失败");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> checkAndSave(MultipartFile communityResidentFile) throws AlertException {
        //不合格的
        List<CommunityResident> failed = new ArrayList<>();
        List<CommunityResident> successNum = new ArrayList<>();
        List<CommunityResident> updateNum = new ArrayList<>();
        List<Integer> faildNum=new ArrayList<>();
        Integer[] num = {2};
        ExcelImportExportUtils.readExcel(CommunityResident.class, communityResidentFile, (communityResident) -> {
            num[0] = num[0] +1;
            try {
                if (Faster.isNull(communityResident)) {
                    throw new AlertException();
                }
                if (Strings.isNotBlank(communityResident.getPhone())) {
                    boolean matches = communityResident.getPhone().matches("^1[0-9]{10}$");
                    if (matches == false) {
                        throw new AlertException("请输入正确的居民电话");
                    }
                }

                if(Strings.isNotBlank(communityResident.getProvince())&&Strings.isNotBlank(communityResident.getCity())
                        &&Strings.isNotBlank(communityResident.getDistrict())){
                    SysDict province = sysDictService.getOne(new QueryWrapper<SysDict>().eq(SysDict.DATA_VALUE, communityResident.getProvince()));
                    SysDict city = sysDictService.getOne(new QueryWrapper<SysDict>().eq(SysDict.DATA_VALUE, communityResident.getCity()));
                    SysDict district = sysDictService.getOne(new QueryWrapper<SysDict>().eq(SysDict.DATA_VALUE, communityResident.getDistrict()));
                    String location = province.getDataKey()+","+city.getDataKey()+","+district.getDataKey();
                    communityResident.setLocation(location);
                }

                if(Strings.isNotBlank(communityResident.getIdCard())){
                    if(communityResident.getIdCard().length()!=15&&communityResident.getIdCard().length()!=18){
                        throw new AlertException("身份证不合法");
                    }
                    List<CommunityResident> communityResidents = communityResidentService.
                            list(new QueryWrapper<CommunityResident>().eq(CommunityResident.ID_CARD, communityResident.getIdCard()));
                    if (communityResidents.size() != 0) {
                        throw new AlertException("该居民已添加");
                    }
                }

                if (Strings.isBlank(communityResident.getBuildCode())) {
                    throw new AlertException("楼编号不许为空");
                }
                String[] split = communityResident.getBuildCode().split("-");
                communityResident.setBuildId(Integer.parseInt(split[1]));

                CommunityBuildDetail one1 = communityBuildDetailService.getOne(new QueryWrapper<CommunityBuildDetail>()
                        .eq(CommunityBuildDetail.BUILD_ID, communityResident.getBuildId())
                        .eq(CommunityBuildDetail.DOOR_PLATE, communityResident.getDoorPlate())
                        .eq(CommunityBuildDetail.UNIT, communityResident.getUnit()));

                if (one1 == null) {
                    throw new AlertException("该户不存在");
                }
                //查户
                CommunityBuildDetail communityBuildDetail = communityBuildDetailService.getOne(new QueryWrapper<CommunityBuildDetail>()
                        .eq(CommunityBuildDetail.ID, one1.getId()));
                if (communityBuildDetail == null) {
                    throw new AlertException("该户没有绑定楼栋");
                }
                communityResident.setUnit(communityBuildDetail.getUnit());
                communityResident.setBuildDetailId(communityBuildDetail.getId());
                CommunityBuild communityBuild = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                        .eq(CommunityBuild.ID, communityBuildDetail.getBuildId()));
                if (communityBuild == null) {
                    throw new AlertException("该户没有绑定建筑");
                }
                communityResident.setBuildId(communityBuild.getId());

                GridInfo gridInfo = gridInfoService.getOne(new QueryWrapper<GridInfo>()
                        .eq(GridInfo.ID, communityBuild.getGridId()));
                if (gridInfo == null) {
                    throw new AlertException("该户没有绑定网格");
                }
                communityResident.setGridId(gridInfo.getId());
                //查出村/社区
                CommunityVillage communityVillage = communityVillageService.getOne(new QueryWrapper<CommunityVillage>()
                        .eq(CommunityVillage.ID, gridInfo.getVillageId()));
                if (null == communityVillage) {
                    throw new AlertException("该户没有绑定村/社区");
                }
                communityResident.setVillageId(communityVillage.getId());
                //查出乡镇
                CommunityTownship communityTownship = communityTownshipService.getOne(new QueryWrapper<CommunityTownship>().eq(CommunityTownship.ID, communityVillage.getTownShipId()));
                if (null == communityTownship) {
                    throw new AlertException("该户没有绑定乡镇");
                }
                communityResident.setTownShipId(communityTownship.getId());

                List<CommunityResident> list = communityResidentService.list(new QueryWrapper<CommunityResident>().eq(CommunityResident.BUILD_DETAIL_ID, communityResident.getBuildDetailId())
                        .eq(CommunityResident.USER_NAME, communityResident.getUserName()));
                if (list.size() != 0) {
                    throw new AlertException("该居民在该户存在重名情况，请确认");
                }

                CommunityResident one = communityResidentService.
                        getOne(new QueryWrapper<CommunityResident>().eq(CommunityResident.ID_CARD, communityResident.getIdCard()));
                if (one == null) {
                    save(communityResident);
                    successNum.add(communityResident);
                } else {
                    communityResident.setId(one.getId());
                    communityResidentService.updateById(communityResident);
                    updateNum.add(communityResident);
                }

            } catch (Exception e) {
                faildNum.add(num[0]);
                failed.add(communityResident);
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("saveNum", successNum.size());
        map.put("updateNum", updateNum.size());
        map.put("failedNum", failed.size());
        map.put("rows",faildNum);
        map.put("list", failed);
        return map;

    }
}
